"""
决策者智能体
负责整合分析结果和建议，做出最终投资决策
"""
from typing import List, Dict, Any, Optional
from langchain.agents import Tool
from loguru import logger
import pandas as pd

from agents.base_agent import BaseInvestmentAgent
from database.data_collector import DataCollector
from utils.stock_analysis import analyze_financial_data, calculate_technical_indicators, calculate_valuation_metrics

class ChiefInvestmentOfficer(BaseInvestmentAgent):
    """首席投资官智能体"""
    
    def __init__(self, verbose: bool = False):
        """初始化首席投资官智能体"""
        from config.settings import AGENT_CONFIG
        name = AGENT_CONFIG["chief_investment_officer"]["name"]
        role = AGENT_CONFIG["chief_investment_officer"]["role"]
        goal = "整合团队分析和建议，做出最终投资决策，为投资组合创造长期稳健收益"
        backstory = f"""
        你是{name}，一位在资产管理行业有25年经验的资深投资专家。
        你曾管理超过百亿规模的基金，经历过多轮牛熊市场，投资业绩长期稳定优异。
        你擅长整合不同观点，从多角度评估市场和个股，能在复杂环境中做出清晰决策。
        你的投资理念注重长期价值和风险控制，同时也善于把握市场情绪和短期机会。
        """
        
        # 创建首席投资官专用工具
        tools = [
            Tool(
                name="evaluate_investment_proposals",
                func=self._evaluate_proposals,
                description="评估多个投资建议方案的优缺点"
            ),
            Tool(
                name="make_investment_decision",
                func=self._make_decision,
                description="基于各方分析和建议做出最终投资决策"
            ),
            Tool(
                name="investment_review",
                func=self._review_investment,
                description="回顾和评估已执行的投资决策成效"
            )
        ]
        tools = [tool.dict() for tool in tools]
        super().__init__(name, role, goal, backstory, tools, verbose)
        logger.info(f"首席投资官 {name} 初始化完成")
    
    def _evaluate_proposals(self, proposals: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        评估投资建议
        
        参数:
            proposals: 投资建议列表
            
        返回:
            评估结果
        """
        logger.info(f"评估 {len(proposals)} 个投资建议")
        
        if not proposals:
            return {
                "evaluations": {},
                "top_rated": None,
                "summary": "无投资建议可评估"
            }
        
        evaluation_results = {}
        ratings = {}
        
        # 获取当前市场环境数据
        data_collector = DataCollector()
        market_data = data_collector.get_index_data("000001")  # 上证指数
        
        # 创建默认市场情绪数据
        market_sentiment = {
            'fear_greed': 50,
            'market_breadth': 50,
            'volatility': 20.0,
            'northbound': 0.0
        }
        
        for i, proposal in enumerate(proposals):
            proposal_id = proposal.get("id", f"proposal_{i}")
            
            # 提取建议的关键信息
            stock_code = proposal.get("stock_code")
            action_type = proposal.get("action_type", "hold")  # buy, sell, hold
            target_weight = proposal.get("target_weight", 0)
            rationale = proposal.get("rationale", "")
            
            # 分析建议的优势和劣势
            strengths = []
            weaknesses = []
            
            # 如果有股票代码，获取股票数据进行分析
            if stock_code:
                try:
                    # 获取股票基本面和技术面数据
                    stock_fundamentals = analyze_financial_data(stock_code)
                    stock_technicals = calculate_technical_indicators(stock_code)
                    
                    # 根据数据分析优势
                    if "profitability" in stock_fundamentals and stock_fundamentals["profitability"]["roe"] > 0.15:
                        strengths.append(f"高ROE({stock_fundamentals['profitability']['roe']:.2%})")
                    
                    if "growth" in stock_fundamentals and stock_fundamentals["growth"]["revenue_growth"] > 0.2:
                        strengths.append(f"收入高增长({stock_fundamentals['growth']['revenue_growth']:.2%})")
                    
                    if "valuation" in stock_fundamentals and stock_fundamentals["valuation"]["pe_ratio"] < 20:
                        strengths.append(f"估值合理(PE {stock_fundamentals['valuation']['pe_ratio']:.2f})")
                    
                    # 分析技术面优势
                    if stock_technicals.get("trend_analysis", {}).get("overall_trend") == "强势上涨":
                        strengths.append("技术面强势")
                    
                    # 分析劣势
                    if "profitability" in stock_fundamentals and stock_fundamentals["profitability"]["net_margin"] < 0.1:
                        weaknesses.append(f"净利率较低({stock_fundamentals['profitability']['net_margin']:.2%})")
                    
                    if "solvency" in stock_fundamentals and stock_fundamentals["solvency"]["debt_to_equity"] > 1:
                        weaknesses.append(f"负债率较高({stock_fundamentals['solvency']['debt_to_equity']:.2f})")
                    
                    if "valuation" in stock_fundamentals and stock_fundamentals["valuation"]["pe_ratio"] > 50:
                        weaknesses.append(f"估值偏高(PE {stock_fundamentals['valuation']['pe_ratio']:.2f})")
                    
                    if stock_technicals.get("trend_analysis", {}).get("overall_trend") == "强势下跌":
                        weaknesses.append("技术面弱势")
                        
                except Exception as e:
                    logger.error(f"分析股票 {stock_code} 数据失败: {e}")
                    weaknesses.append("数据分析失败")
            
            # 如果没有提取到足够的优势和劣势，添加基于建议理由的分析
            if len(strengths) < 2 and rationale:
                if "低估" in rationale or "价值" in rationale:
                    strengths.append("可能存在价值低估")
                if "成长" in rationale or "前景" in rationale:
                    strengths.append("具有良好成长前景")
                    
            if len(weaknesses) < 2 and rationale:
                if "风险" in rationale or "不确定" in rationale:
                    weaknesses.append("存在一定风险因素")
                if "竞争" in rationale or "压力" in rationale:
                    weaknesses.append("面临竞争压力")
            
            # 确保至少有一项优势和劣势
            if not strengths:
                strengths.append("建议理由合理")
            if not weaknesses:
                weaknesses.append("缺乏详细论证")
            
            # 计算与当前策略的一致性
            # 这里可以根据实际情况调整评分标准
            alignment_score = 0.7  # 默认中等一致性
            
            # 根据市场情绪调整风险评估
            risk_score = 0.5  # 默认中等风险
            if market_sentiment and "fear_greed" in market_sentiment:
                # 恐惧贪婪指数高时风险增加
                fear_greed = market_sentiment["fear_greed"] / 100.0
                risk_score = 0.3 + fear_greed * 0.4  # 将风险分数映射到0.3-0.7范围
            
            # 计算综合评分
            overall_rating = 3.0  # 默认中等评分
            
            # 根据优势数量加分
            overall_rating += min(len(strengths) * 0.5, 1.0)
            
            # 根据劣势数量减分
            overall_rating -= min(len(weaknesses) * 0.3, 0.9)
            
            # 根据与策略一致性调整
            overall_rating += (alignment_score - 0.5) * 2
            
            # 根据风险评分调整
            overall_rating -= (risk_score - 0.5) * 1.5
            
            # 确保评分在1-5范围内
            overall_rating = max(1.0, min(5.0, overall_rating))
            
            # 保存评估结果
            evaluation_results[proposal_id] = {
                "strengths": strengths,
                "weaknesses": weaknesses,
                "alignment_with_strategy": alignment_score,
                "risk_assessment": risk_score,
                "overall_rating": overall_rating
            }
            
            # 记录评分用于找出最高评分
            ratings[proposal_id] = overall_rating
        
        # 找出评分最高的建议
        top_rated = max(ratings.items(), key=lambda x: x[1])[0] if ratings else None
        
        # 生成总结
        # 确保market_sentiment不为None
        market_sentiment_data = market_sentiment or {}
        summary = self._generate_evaluation_summary(evaluation_results, market_sentiment_data)
        
        return {
            "evaluations": evaluation_results,
            "top_rated": top_rated,
            "summary": summary
        }
        
    def _generate_evaluation_summary(self, evaluations: Dict[str, Any], market_sentiment: Dict[str, Any]) -> str:
        """生成评估总结"""
        if not evaluations:
            return "无投资建议可评估"
            
        # 计算平均评分
        avg_rating = sum(e["overall_rating"] for e in evaluations.values()) / len(evaluations)
        
        # 统计行业偏好
        industry_preference = "多元化"
        
        # 根据市场情绪调整总结
        sentiment_desc = "中性"
        if market_sentiment:
            fear_greed = market_sentiment.get("fear_greed", 50)
            if fear_greed > 70:
                sentiment_desc = "过度乐观"
            elif fear_greed < 30:
                sentiment_desc = "过度悲观"
                
        # 生成总结
        if avg_rating > 4.0:
            return f"多数建议质量较高，市场情绪{sentiment_desc}，建议适度采纳高评分建议"
        elif avg_rating > 3.0:
            return f"建议质量中等，市场情绪{sentiment_desc}，需谨慎选择并控制仓位"
        else:
            return f"建议质量较低，市场情绪{sentiment_desc}，建议保持观望或寻求更多信息"
    
    def _make_decision(self, analysis_reports: Dict[str, Any], market_conditions: Dict[str, Any]) -> Dict[str, Any]:
        """
        做出投资决策
        
        参数:
            analysis_reports: 分析报告集合
            market_conditions: 市场状况
            
        返回:
            投资决策
        """
        logger.info("做出投资决策")
        
        # 检查输入数据
        if not analysis_reports or not market_conditions:
            logger.warning("缺少分析报告或市场状况数据")
            return {
                "decision_type": "hold",
                "actions": [],
                "sector_allocation": {},
                "cash_position": 0.2,
                "hedging_strategy": "无",
                "expected_return": 0.0,
                "risk_level": "低"
            }
        
        # 提取市场趋势信息
        market_trend = market_conditions.get("trend", {})
        trend_direction = market_trend.get("trend_direction", "盘整")
        trend_strength = market_trend.get("strength", 0)
        market_sentiment = market_conditions.get("sentiment", {})
        
        # 提取行业分析信息
        sector_analysis = analysis_reports.get("sector_analysis", {})
        hot_sectors = sector_analysis.get("hot_sectors", [])
        cooling_sectors = sector_analysis.get("cooling_sectors", [])
        
        # 提取个股分析信息
        stock_analysis = analysis_reports.get("stock_analysis", {})
        
        # 根据市场趋势确定决策类型
        if trend_direction == "上涨" and trend_strength > 60:
            decision_type = "aggressive_buy"
        elif trend_direction == "上涨" and trend_strength > 30:
            decision_type = "moderate_buy"
        elif trend_direction == "下跌" and trend_strength > 60:
            decision_type = "defensive"
        elif trend_direction == "下跌" and trend_strength > 30:
            decision_type = "selective_sell"
        else:
            decision_type = "portfolio_adjustment"
        
        # 生成具体操作建议
        actions = []
        
        # 处理买入建议
        if decision_type in ["aggressive_buy", "moderate_buy", "portfolio_adjustment"]:
            # 从热门行业中选择表现良好的股票
            for sector_info in hot_sectors[:2]:  # 取前两个热门行业
                sector_name = sector_info.get("industry", "")
                # 从该行业选择基本面和技术面都不错的股票
                sector_stocks = self._get_sector_stocks(sector_name, stock_analysis)
                for stock in sector_stocks[:2]:  # 每个行业取前两只股票
                    weight = 0.05 if decision_type == "aggressive_buy" else 0.03
                    actions.append({
                        "type": "buy",
                        "stock_code": stock["code"],
                        "weight": weight,
                        "reasoning": f"{sector_name}行业前景看好，{stock.get('name', '')}基本面良好"
                    })
        
        # 处理卖出建议
        if decision_type in ["defensive", "selective_sell", "portfolio_adjustment"]:
            # 从降温行业中选择表现不佳的股票
            for sector_info in cooling_sectors[:2]:  # 取前两个降温行业
                sector_name = sector_info.get("industry", "")
                # 从该行业选择基本面或技术面较差的股票
                sector_stocks = self._get_weak_sector_stocks(sector_name, stock_analysis)
                for stock in sector_stocks[:1]:  # 每个行业取一只股票
                    weight = 0.03 if decision_type == "defensive" else 0.02
                    actions.append({
                        "type": "sell",
                        "stock_code": stock["code"],
                        "weight": weight,
                        "reasoning": f"{sector_name}行业降温，{stock.get('name', '')}表现不及预期"
                    })
        
        # 添加持有建议
        # 选择一些核心资产保持持有
        core_holdings = self._get_core_holdings(stock_analysis)
        for stock in core_holdings[:3]:
            actions.append({
                "type": "hold",
                "stock_code": stock["code"],
                "weight": 0.1,
                "reasoning": f"{stock.get('name', '')}为核心资产，基本面稳健"
            })
        
        # 计算行业配置
        sector_allocation = self._calculate_sector_allocation(hot_sectors, cooling_sectors, decision_type)
        
        # 确定现金仓位
        cash_position = 0.1
        if decision_type == "defensive":
            cash_position = 0.25
        elif decision_type == "aggressive_buy":
            cash_position = 0.05
        
        # 确定对冲策略
        hedging_strategy = "无"
        if trend_direction == "下跌" and trend_strength > 40:
            hedging_strategy = "部分指数期货对冲"
        elif market_sentiment.get("volatility", 20) > 30:
            hedging_strategy = "波动率对冲"
        
        # 估计预期收益和风险水平
        expected_return = 0.08  # 默认预期收益
        if decision_type == "aggressive_buy":
            expected_return = 0.15
        elif decision_type == "defensive":
            expected_return = 0.05
        
        risk_level = "中等"
        if decision_type == "aggressive_buy":
            risk_level = "高"
        elif decision_type == "defensive":
            risk_level = "低"
        
        return {
            "decision_type": decision_type,
            "actions": actions,
            "sector_allocation": sector_allocation,
            "cash_position": cash_position,
            "hedging_strategy": hedging_strategy,
            "expected_return": expected_return,
            "risk_level": risk_level
        }
    
    def _get_sector_stocks(self, sector_name: str, stock_analysis: Dict[str, Any]) -> List[Dict[str, Any]]:
        """获取行业内表现良好的股票"""
        # 实际应用中应该从股票池中筛选该行业的股票并进行排序
        # 这里简化处理，返回一些示例股票
        sector_stocks = []
        
        # 获取股票列表
        data_collector = DataCollector()
        stock_list = data_collector.get_stock_list()
        
        # 筛选行业股票
        if not stock_list.empty:
            sector_stocks_df = stock_list[stock_list['industry'] == sector_name]
            for _, row in sector_stocks_df.iterrows():
                sector_stocks.append({
                    "code": row['code'],
                    "name": row['name']
                })
        
        # 如果没有找到行业股票，返回一些示例
        if not sector_stocks:
            if sector_name == "银行":
                return [{"code": "600036", "name": "招商银行"}, {"code": "601398", "name": "工商银行"}]
            elif sector_name == "科技":
                return [{"code": "000063", "name": "中兴通讯"}, {"code": "002415", "name": "海康威视"}]
            elif sector_name == "消费":
                return [{"code": "600519", "name": "贵州茅台"}, {"code": "000858", "name": "五粮液"}]
            elif sector_name == "医疗":
                return [{"code": "600276", "name": "恒瑞医药"}, {"code": "300015", "name": "爱尔眼科"}]
            else:
                return [{"code": "601318", "name": "中国平安"}, {"code": "600030", "name": "中信证券"}]
        
        return sector_stocks
    
    def _get_weak_sector_stocks(self, sector_name: str, stock_analysis: Dict[str, Any]) -> List[Dict[str, Any]]:
        """获取行业内表现较弱的股票"""
        # 与_get_sector_stocks类似，但返回表现较弱的股票
        sector_stocks = self._get_sector_stocks(sector_name, stock_analysis)
        # 实际应用中应该根据基本面和技术面指标排序
        # 这里简化处理，返回列表中的后半部分
        return sector_stocks[len(sector_stocks)//2:]
    
    def _get_core_holdings(self, stock_analysis: Dict[str, Any]) -> List[Dict[str, Any]]:
        """获取核心持仓股票"""
        # 实际应用中应该从股票池中筛选基本面稳健的核心资产
        # 这里简化处理，返回一些示例核心资产
        return [
            {"code": "600519", "name": "贵州茅台"},
            {"code": "601318", "name": "中国平安"},
            {"code": "600036", "name": "招商银行"},
            {"code": "000333", "name": "美的集团"},
            {"code": "600276", "name": "恒瑞医药"}
        ]
    
    def _calculate_sector_allocation(self, hot_sectors: List[Dict[str, Any]],
                                    cooling_sectors: List[Dict[str, Any]],
                                    decision_type: str) -> Dict[str, float]:
        """计算行业配置比例"""
        # 基础配置
        allocation = {
            "科技": 0.25,
            "消费": 0.20,
            "金融": 0.15,
            "医疗": 0.15,
            "其他": 0.25
        }
        
        # 根据热门行业调整配置
        for sector_info in hot_sectors:
            sector_name = sector_info.get("industry", "")
            if sector_name in allocation:
                # 增加热门行业配置
                increase = 0.05 if decision_type == "aggressive_buy" else 0.03
                allocation[sector_name] += increase
        
        # 根据降温行业调整配置
        for sector_info in cooling_sectors:
            sector_name = sector_info.get("industry", "")
            if sector_name in allocation:
                # 减少降温行业配置
                decrease = 0.05 if decision_type == "defensive" else 0.03
                allocation[sector_name] = max(0.05, allocation[sector_name] - decrease)
        
        # 确保总和为1
        total = sum(allocation.values())
        if total > 0:
            allocation = {k: v/total for k, v in allocation.items()}
        
        return allocation
    
    def _review_investment(self, portfolio_performance: Dict[str, Any]) -> Dict[str, Any]:
        """
        回顾投资表现
        
        参数:
            portfolio_performance: 投资组合表现数据
            
        返回:
            投资回顾和改进建议
        """
        logger.info("回顾投资表现")
        
        # 检查输入数据
        if not portfolio_performance:
            logger.warning("缺少投资组合表现数据")
            return {
                "performance_assessment": {
                    "return_vs_benchmark": "无数据",
                    "risk_adjusted_return": "无数据",
                    "attribution_analysis": {}
                },
                "key_learnings": ["数据不足，无法进行有效分析"],
                "improvement_suggestions": ["完善数据收集系统"]
            }
        
        # 提取表现数据
        total_return = portfolio_performance.get("total_return", 0)
        benchmark_return = portfolio_performance.get("benchmark_return", 0)
        
        # 计算相对收益
        relative_return = total_return - benchmark_return
        relative_return_str = f"+{relative_return:.1%}" if relative_return > 0 else f"{relative_return:.1%}"
        
        # 提取风险指标
        volatility = portfolio_performance.get("volatility", 0)
        max_drawdown = portfolio_performance.get("max_drawdown", 0)
        sharpe_ratio = portfolio_performance.get("sharpe_ratio", 0)
        
        # 评估风险调整后收益
        risk_adjusted_return = "一般"
        if sharpe_ratio > 1.5:
            risk_adjusted_return = "优秀"
        elif sharpe_ratio > 1.0:
            risk_adjusted_return = "良好"
        elif sharpe_ratio < 0.5:
            risk_adjusted_return = "较差"
        
        # 提取归因分析数据
        attribution = portfolio_performance.get("attribution", {})
        asset_allocation_contrib = attribution.get("asset_allocation", 0)
        stock_selection_contrib = attribution.get("stock_selection", 0)
        market_timing_contrib = attribution.get("market_timing", 0)
        
        # 如果没有归因数据，进行简单估计
        if not attribution:
            # 假设60%来自选股，30%来自资产配置，10%来自择时
            asset_allocation_contrib = total_return * 0.3
            stock_selection_contrib = total_return * 0.6
            market_timing_contrib = total_return * 0.1
        
        # 格式化归因数据
        asset_allocation_str = f"+{asset_allocation_contrib:.1%}" if asset_allocation_contrib > 0 else f"{asset_allocation_contrib:.1%}"
        stock_selection_str = f"+{stock_selection_contrib:.1%}" if stock_selection_contrib > 0 else f"{stock_selection_contrib:.1%}"
        market_timing_str = f"+{market_timing_contrib:.1%}" if market_timing_contrib > 0 else f"{market_timing_contrib:.1%}"
        
        # 分析行业表现
        sector_performance = portfolio_performance.get("sector_performance", {})
        best_sectors = []
        worst_sectors = []
        
        if sector_performance:
            # 按表现排序行业
            sorted_sectors = sorted(sector_performance.items(), key=lambda x: x[1], reverse=True)
            best_sectors = [s[0] for s in sorted_sectors[:2]]
            worst_sectors = [s[0] for s in sorted_sectors[-2:]]
        
        # 生成关键经验
        key_learnings = []
        
        if best_sectors:
            key_learnings.append(f"{best_sectors[0]}行业选股效果优于预期")
        
        if market_timing_contrib < 0:
            key_learnings.append("市场时机把握有待改进")
        
        if max_drawdown > 0.15:
            key_learnings.append("止损策略执行不够及时")
        
        if volatility > 0.2:
            key_learnings.append("组合波动率较高，需加强风险控制")
            
        if stock_selection_contrib > asset_allocation_contrib * 2:
            key_learnings.append("个股选择贡献显著高于资产配置，可考虑集中持股策略")
            
        if worst_sectors:
            key_learnings.append(f"{worst_sectors[0]}行业表现不及预期，需重新评估")
            
        # 如果没有足够的关键经验，添加一些通用的
        if len(key_learnings) < 3:
            key_learnings.append("需要更全面的投资组合分析系统")
            
        # 确保至少有3条关键经验
        key_learnings = key_learnings[:5]  # 最多5条
        
        # 生成改进建议
        improvement_suggestions = []
        
        if max_drawdown > 0.15:
            improvement_suggestions.append("完善止损机制，设置更严格的止损纪律")
            
        if market_timing_contrib < 0:
            improvement_suggestions.append("增强对宏观经济指标的跟踪，改进市场择时策略")
            
        if volatility > 0.2:
            improvement_suggestions.append("增加低相关性资产，降低组合整体波动")
            
        if worst_sectors:
            improvement_suggestions.append(f"减少{worst_sectors[0]}行业配置，或更谨慎选择该行业个股")
            
        if sharpe_ratio < 1.0:
            improvement_suggestions.append("优化资产配置模型参数，提高风险调整后收益")
            
        # 如果没有足够的改进建议，添加一些通用的
        if len(improvement_suggestions) < 3:
            improvement_suggestions.append("建立更系统的投资决策流程")
            improvement_suggestions.append("加强投资团队协作，提高信息共享效率")
            
        # 确保至少有3条改进建议
        improvement_suggestions = improvement_suggestions[:5]  # 最多5条
        
        return {
            "performance_assessment": {
                "return_vs_benchmark": relative_return_str,
                "risk_adjusted_return": risk_adjusted_return,
                "attribution_analysis": {
                    "asset_allocation": asset_allocation_str,
                    "stock_selection": stock_selection_str,
                    "market_timing": market_timing_str
                }
            },
            "key_learnings": key_learnings,
            "improvement_suggestions": improvement_suggestions
        }


class ResearchSpecialist(BaseInvestmentAgent):
    """研究专员智能体"""
    
    def __init__(self, specialization: str = "科技", verbose: bool = False):
        """
        初始化研究专员智能体
        
        参数:
            specialization: 专精领域/行业
        """
        
        from config.settings import AGENT_CONFIG
        name = "吴雨晨"
        role = f"{specialization}行业研究专员"
        goal = f"深入研究{specialization}行业动态和公司发展，发掘投资机会"
        backstory = f"""
        你是吴雨晨，一位专注于{specialization}行业的研究专员，拥有8年研究经验。
        你曾在知名券商研究所担任行业分析师，发表过多篇有影响力的研究报告。
        你对{specialization}行业的产业链、竞争格局和技术发展趋势有深入了解。
        你善于挖掘行业中被低估的公司和具有前瞻性商业模式的创新企业。
        """
        
        # 创建研究专员专用工具
        tools = [
            Tool(
                name="industry_research",
                func=self._research_industry,
                description=f"研究{specialization}行业的发展趋势、竞争格局和政策环境"
            ),
            Tool(
                name="company_deep_dive",
                func=self._deep_dive_company,
                description="对特定公司进行深入研究，包括商业模式、核心竞争力和成长潜力"
            ),
            Tool(
                name="thematic_research",
                func=self._research_theme,
                description="研究特定主题或投资线索，发掘相关投资机会"
            )
        ]
        tools = [tool.dict() for tool in tools]
        self.specialization = specialization
        
        super().__init__(name, role, goal, backstory, tools, verbose)
        logger.info(f"{specialization}行业研究专员 {name} 初始化完成")
    
    def _research_industry(self) -> Dict[str, Any]:
        """
        行业研究
        
        返回:
            行业研究报告
        """
        logger.info(f"研究{self.specialization}行业")
        
        try:
            # 获取行业数据
            data_collector = DataCollector()
            industry_stocks = []
            
            # 获取股票列表
            stock_list = data_collector.get_stock_list()
            if not stock_list.empty:
                # 筛选该行业的股票
                industry_stocks_df = stock_list[stock_list['industry'] == self.specialization]
                industry_stocks = industry_stocks_df['code'].tolist()
            
            # 如果没有找到行业股票，使用一些示例股票
            if not industry_stocks:
                if self.specialization == "银行":
                    industry_stocks = ["600036", "601398", "601288"]
                elif self.specialization == "科技":
                    industry_stocks = ["000063", "002415", "600100"]
                elif self.specialization == "消费":
                    industry_stocks = ["600519", "000858", "600887"]
                elif self.specialization == "医疗":
                    industry_stocks = ["600276", "300015", "603259"]
                else:
                    industry_stocks = ["601318", "600030", "601166"]
            
            # 分析行业增长率
            growth_rate = self._calculate_industry_growth_rate(industry_stocks)
            
            # 获取行业龙头企业
            leader_companies = self._get_industry_leaders(industry_stocks)
            
            # 获取行业新兴企业
            rising_stars = self._get_rising_stars(industry_stocks)
            
            # 计算行业集中度
            concentration_ratio = self._calculate_concentration_ratio(industry_stocks)
            
            # 分析行业驱动因素
            key_drivers = self._analyze_industry_drivers()
            
            # 分析行业挑战
            challenges = self._analyze_industry_challenges()
            
            # 分析行业政策法规
            regulations = self._analyze_industry_regulations()
            
            # 分析行业未来趋势
            future_trends = self._analyze_future_trends()
            
            # 生成投资启示
            investment_implications = self._generate_investment_implications(
                growth_rate, key_drivers, challenges, future_trends
            )
            
            return {
                "industry_overview": self._generate_industry_overview(),
                "growth_rate": growth_rate,
                "key_drivers": key_drivers,
                "challenges": challenges,
                "regulations": regulations,
                "competitive_landscape": {
                    "leader_companies": leader_companies,
                    "rising_stars": rising_stars,
                    "concentration_ratio": concentration_ratio
                },
                "future_trends": future_trends,
                "investment_implications": investment_implications
            }
            
        except Exception as e:
            logger.error(f"行业研究失败: {e}")
            # 返回基本信息
            return {
                "industry_overview": f"{self.specialization}行业概述 (数据获取失败)",
                "growth_rate": None,
                "key_drivers": ["数据不足"],
                "challenges": ["数据不足"],
                "regulations": "数据不足",
                "competitive_landscape": {
                    "leader_companies": [],
                    "rising_stars": [],
                    "concentration_ratio": None
                },
                "future_trends": ["数据不足"],
                "investment_implications": "数据不足，无法提供投资建议"
            }
    
    def _calculate_industry_growth_rate(self, industry_stocks: List[str]) -> float:
        """计算行业增长率"""
        try:
            # 获取行业公司的财务数据
            data_collector = DataCollector()
            growth_rates = []
            
            for stock_code in industry_stocks[:5]:  # 取前5家公司
                financials = data_collector.get_financial_data(stock_code)
                if not financials.empty and "growth" in financials.columns:
                    company_growth = financials["growth"].mean()
                    if not pd.isna(company_growth):
                        growth_rates.append(company_growth)
            
            # 计算平均增长率
            if growth_rates:
                return sum(growth_rates) / len(growth_rates)
            
            # 如果没有数据，返回行业默认增长率
            if self.specialization == "科技":
                return 18.5
            elif self.specialization == "医疗":
                return 15.2
            elif self.specialization == "消费":
                return 10.8
            elif self.specialization == "金融":
                return 8.5
            else:
                return 12.0
                
        except Exception as e:
            logger.error(f"计算行业增长率失败: {e}")
            return 10.0  # 默认增长率
    
    def _get_industry_leaders(self, industry_stocks: List[str]) -> List[Dict[str, str]]:
        """获取行业龙头企业"""
        try:
            # 获取行业公司的市值数据
            data_collector = DataCollector()
            companies = []
            
            for stock_code in industry_stocks:
                stock_data = data_collector.get_daily_data(stock_code)
                if not stock_data.empty:
                    # 获取公司名称
                    stock_list = data_collector.get_stock_list()
                    stock_name = stock_list[stock_list['code'] == stock_code]['name'].iloc[0] if not stock_list.empty else "未知公司"
                    
                    # 计算市值
                    if '收盘' in stock_data.columns and '成交量' in stock_data.columns:
                        market_cap = stock_data['收盘'].iloc[-1] * stock_data['成交量'].iloc[-1]
                        companies.append({
                            "code": stock_code,
                            "name": stock_name,
                            "market_cap": market_cap
                        })
            
            # 按市值排序
            sorted_companies = sorted(companies, key=lambda x: x.get('market_cap', 0), reverse=True)
            
            # 返回前3家龙头企业
            leaders = []
            for company in sorted_companies[:3]:
                leaders.append({
                    "code": company["code"],
                    "name": company["name"]
                })
            
            # 如果没有足够的数据，返回行业默认龙头
            if not leaders:
                if self.specialization == "科技":
                    return [{"code": "000063", "name": "中兴通讯"}, {"code": "002415", "name": "海康威视"}]
                elif self.specialization == "医疗":
                    return [{"code": "600276", "name": "恒瑞医药"}, {"code": "300015", "name": "爱尔眼科"}]
                elif self.specialization == "消费":
                    return [{"code": "600519", "name": "贵州茅台"}, {"code": "000858", "name": "五粮液"}]
                elif self.specialization == "金融":
                    return [{"code": "601318", "name": "中国平安"}, {"code": "600036", "name": "招商银行"}]
                else:
                    return [{"code": "行业龙头1", "name": "行业龙头1"}, {"code": "行业龙头2", "name": "行业龙头2"}]
            
            return leaders
            
        except Exception as e:
            logger.error(f"获取行业龙头企业失败: {e}")
            return [{"code": "行业龙头1", "name": "行业龙头1"}, {"code": "行业龙头2", "name": "行业龙头2"}]
    
    def _get_rising_stars(self, industry_stocks: List[str]) -> List[Dict[str, str]]:
        """获取行业新兴企业"""
        try:
            # 获取行业公司的增长率数据
            data_collector = DataCollector()
            companies = []
            
            for stock_code in industry_stocks:
                financials = data_collector.get_financial_data(stock_code)
                if not financials.empty:
                    # 获取公司名称
                    stock_list = data_collector.get_stock_list()
                    stock_name = stock_list[stock_list['code'] == stock_code]['name'].iloc[0] if not stock_list.empty else "未知公司"
                    
                    # 计算收入增长率
                    if "growth" in financials.columns and "revenue_growth" in financials.columns:
                        revenue_growth = financials["revenue_growth"].mean()
                        companies.append({
                            "code": stock_code,
                            "name": stock_name,
                            "growth": revenue_growth
                        })
            
            # 按增长率排序
            sorted_companies = sorted(companies, key=lambda x: x.get('growth', 0), reverse=True)
            
            # 返回增长最快的3家企业
            rising_stars = []
            for company in sorted_companies[:3]:
                rising_stars.append({
                    "code": company["code"],
                    "name": company["name"]
                })
            
            # 如果没有足够的数据，返回行业默认新兴企业
            if not rising_stars:
                if self.specialization == "科技":
                    return [{"code": "300750", "name": "宁德时代"}, {"code": "688981", "name": "中芯国际"}]
                elif self.specialization == "医疗":
                    return [{"code": "688180", "name": "君实生物"}, {"code": "688166", "name": "博瑞医药"}]
                elif self.specialization == "消费":
                    return [{"code": "603195", "name": "公牛集团"}, {"code": "603486", "name": "科沃斯"}]
                elif self.specialization == "金融":
                    return [{"code": "688561", "name": "奇安信"}, {"code": "688561", "name": "东方财富"}]
                else:
                    return [{"code": "新兴企业1", "name": "新兴企业1"}, {"code": "新兴企业2", "name": "新兴企业2"}]
            
            return rising_stars
            
        except Exception as e:
            logger.error(f"获取行业新兴企业失败: {e}")
            return [{"code": "新兴企业1", "name": "新兴企业1"}, {"code": "新兴企业2", "name": "新兴企业2"}]
    
    def _calculate_concentration_ratio(self, industry_stocks: List[str]) -> float:
        """计算行业集中度"""
        try:
            # 获取行业公司的市值数据
            data_collector = DataCollector()
            market_caps = []
            
            for stock_code in industry_stocks:
                stock_data = data_collector.get_daily_data(stock_code)
                if not stock_data.empty and '收盘' in stock_data.columns and '成交量' in stock_data.columns:
                    market_cap = stock_data['收盘'].iloc[-1] * stock_data['成交量'].iloc[-1]
                    market_caps.append(market_cap)
            
            # 计算CR4集中度（前4家企业市值占比）
            if market_caps:
                market_caps.sort(reverse=True)
                top4_market_cap = sum(market_caps[:4])
                total_market_cap = sum(market_caps)
                if total_market_cap > 0:
                    return top4_market_cap / total_market_cap
            
            # 如果没有数据，返回行业默认集中度
            if self.specialization == "科技":
                return 0.35
            elif self.specialization == "医疗":
                return 0.40
            elif self.specialization == "消费":
                return 0.55
            elif self.specialization == "金融":
                return 0.65
            else:
                return 0.45
                
        except Exception as e:
            logger.error(f"计算行业集中度失败: {e}")
            return 0.45  # 默认集中度
    
    def _analyze_industry_drivers(self) -> List[str]:
        """分析行业驱动因素"""
        # 根据行业返回驱动因素
        if self.specialization == "科技":
            return ["技术创新与迭代加速", "数字化转型需求增长", "政策支持与补贴"]
        elif self.specialization == "医疗":
            return ["人口老龄化趋势", "医疗保障体系完善", "创新药研发突破"]
        elif self.specialization == "消费":
            return ["消费升级趋势", "新零售模式兴起", "品牌溢价能力增强"]
        elif self.specialization == "金融":
            return ["金融科技应用扩展", "资管新规落地", "利率市场化改革"]
        else:
            return ["产业政策支持", "技术创新驱动", "消费需求变化"]
    
    def _analyze_industry_challenges(self) -> List[str]:
        """分析行业挑战"""
        # 根据行业返回挑战
        if self.specialization == "科技":
            return ["研发投入压力大", "人才竞争激烈", "国际贸易摩擦"]
        elif self.specialization == "医疗":
            return ["带量采购降价压力", "研发周期长", "监管趋严"]
        elif self.specialization == "消费":
            return ["线上竞争加剧", "获客成本上升", "消费信心波动"]
        elif self.specialization == "金融":
            return ["不良资产风险", "利润空间收窄", "监管合规要求提高"]
        else:
            return ["成本上升压力", "市场竞争加剧", "政策不确定性"]
    
    def _analyze_industry_regulations(self) -> str:
        """分析行业政策法规"""
        # 根据行业返回政策法规分析
        if self.specialization == "科技":
            return "近期政策重点支持芯片、人工智能等关键领域，同时加强数据安全和隐私保护监管。《新一代人工智能发展规划》和《软件和信息技术服务业发展规划》为行业提供了明确的发展方向。"
        elif self.specialization == "医疗":
            return "医改持续深化，带量采购常态化，创新药优先审评审批政策支持研发创新。《健康中国2030规划纲要》和《医药工业发展规划指南》为行业长期发展提供了政策保障。"
        elif self.specialization == "消费":
            return "消费促进政策频出，电商法规范市场秩序，直播电商新规加强监管。《关于促进消费扩容提质加快形成强大国内市场的实施意见》为消费升级提供了政策支持。"
        elif self.specialization == "金融":
            return "金融开放加速，资管新规落地，强化金融风险防控。《关于金融支持实体经济发展的指导意见》和《关于规范金融机构资产管理业务的指导意见》为行业发展提供了政策框架。"
        else:
            return f"{self.specialization}行业相关政策法规主要围绕产业升级、创新驱动和规范市场秩序三个方面，总体呈现鼓励发展、规范管理的特点。"
    
    def _analyze_future_trends(self) -> List[str]:
        """分析行业未来趋势"""
        # 根据行业返回未来趋势
        if self.specialization == "科技":
            return ["AI技术深度应用", "云计算向边缘计算延伸", "国产替代加速"]
        elif self.specialization == "医疗":
            return ["精准医疗普及", "医疗数字化转型", "创新药研发提速"]
        elif self.specialization == "消费":
            return ["品质消费升级", "新零售全渠道融合", "国潮品牌崛起"]
        elif self.specialization == "金融":
            return ["金融科技深化应用", "财富管理需求增长", "绿色金融发展"]
        else:
            return ["产业链升级整合", "数字化转型加速", "可持续发展理念普及"]
    
    def _generate_industry_overview(self) -> str:
        """生成行业概述"""
        # 根据行业生成概述
        if self.specialization == "科技":
            return "科技行业是国民经济的战略性支柱产业，涵盖信息技术、电子设备、软件服务等多个细分领域。近年来，在数字经济浪潮和政策支持下，行业保持快速增长，特别是在人工智能、云计算、大数据等新兴领域表现突出。行业整体呈现出技术迭代加速、应用场景丰富、产业链协同发展的特点。"
        elif self.specialization == "医疗":
            return "医疗行业是关系国计民生的重要产业，包括医药制造、医疗器械、医疗服务等细分领域。在人口老龄化、医保体系完善和技术创新的驱动下，行业需求稳定增长。近年来，创新药研发、高端医疗器械国产化和互联网医疗等领域发展迅速，行业结构不断优化升级。"
        elif self.specialization == "消费":
            return "消费行业是国民经济的基础性产业，涵盖食品饮料、家电、服装、日用品等多个领域。随着居民收入增长和消费升级，行业呈现品质化、个性化、多元化发展趋势。新零售模式兴起，线上线下融合加速，品牌竞争日益激烈，消费者体验成为企业竞争的关键因素。"
        elif self.specialization == "金融":
            return "金融行业是现代经济的核心产业，包括银行、证券、保险、资产管理等细分领域。在金融开放、科技赋能和监管规范的背景下，行业正经历深刻变革。传统金融机构加速数字化转型，金融科技企业快速崛起，行业竞争格局和盈利模式面临重构。"
        else:
            return f"{self.specialization}行业是国民经济的重要组成部分，近年来在政策支持和市场需求的双重驱动下保持稳定发展。行业内部结构不断优化，创新能力持续提升，龙头企业的市场地位进一步巩固，行业整体呈现出良好的发展态势。"
    
    def _generate_investment_implications(self, growth_rate: float, key_drivers: List[str],
                                         challenges: List[str], future_trends: List[str]) -> str:
        """生成投资启示"""
        # 根据行业分析结果生成投资启示
        investment_stance = "积极" if growth_rate > 15 else "中性" if growth_rate > 10 else "谨慎"
        
        implications = f"对{self.specialization}行业持{investment_stance}投资态度。"
        
        # 添加投资策略
        implications += f"行业年均增长率约{growth_rate:.1f}%，"
        
        if investment_stance == "积极":
            implications += "建议超配该行业，重点关注以下投资机会："
        elif investment_stance == "中性":
            implications += "建议标配该行业，选择性关注以下投资机会："
        else:
            implications += "建议低配该行业，仅关注以下优质标的："
        
        # 添加具体投资方向
        implications += f"1) {future_trends[0] if future_trends else '行业龙头企业'}；"
        if len(future_trends) > 1:
            implications += f"2) {future_trends[1]}；"
        implications += f"3) {key_drivers[0] if key_drivers else '具有核心竞争力的企业'}。"
        
        # 添加风险提示
        implications += f"需警惕{challenges[0] if challenges else '行业竞争加剧'}带来的风险。"
        
        return implications
    
    def _deep_dive_company(self, company_code: str) -> Dict[str, Any]:
        """
        公司深度研究
        
        参数:
            company_code: 公司股票代码
            
        返回:
            公司深度研究报告
        """
        logger.info(f"对公司 {company_code} 进行深度研究")
        
        try:
            # 获取公司基本信息
            data_collector = DataCollector()
            stock_list = data_collector.get_stock_list()
            company_name = "未知公司"
            company_industry = "未知行业"
            
            if not stock_list.empty:
                company_info = stock_list[stock_list['code'] == company_code]
                if not company_info.empty:
                    company_name = company_info['name'].iloc[0]
                    company_industry = company_info['industry'].iloc[0]
            
            # 获取公司财务数据
            financials = data_collector.get_financial_data(company_code)
            
            # 获取公司股价数据
            price_data = data_collector.get_daily_data(company_code)
            
            # 分析公司基本面
            fundamentals = analyze_financial_data(company_code)
            
            # 分析公司技术面
            technicals = calculate_technical_indicators(company_code)
            
            # 分析公司估值
            valuation = calculate_valuation_metrics(company_code)
            
            # 生成公司概况
            company_profile = self._generate_company_profile(company_name, company_industry)
            
            # 分析商业模式
            business_model = self._analyze_business_model(company_code, company_industry)
            
            # 分析产品和服务
            products_services = self._analyze_products_services(company_code, company_industry)
            
            # 分析竞争优势
            competitive_advantages = self._analyze_competitive_advantages(fundamentals)
            
            # 评估管理层质量
            management_quality = self._evaluate_management_quality(company_code, fundamentals)
            
            # 提取财务分析数据
            financial_analysis = self._extract_financial_analysis(fundamentals)
            
            # 分析风险因素
            risks = self._analyze_risks(company_code, fundamentals, technicals)
            
            # 提取估值数据
            valuation_data = self._extract_valuation_data(valuation, company_industry)
            
            # 生成投资论点
            investment_thesis = self._generate_investment_thesis(
                company_name, fundamentals, technicals, valuation
            )
            
            return {
                "company_profile": company_profile,
                "business_model": business_model,
                "products_services": products_services,
                "competitive_advantages": competitive_advantages,
                "management_quality": management_quality,
                "financial_analysis": financial_analysis,
                "risks": risks,
                "valuation": valuation_data,
                "investment_thesis": investment_thesis
            }
            
        except Exception as e:
            logger.error(f"公司深度研究失败: {e}")
            # 返回基本信息
            return {
                "company_profile": f"公司代码: {company_code} (数据获取失败)",
                "business_model": "数据不足，无法分析",
                "products_services": ["数据不足"],
                "competitive_advantages": ["数据不足"],
                "management_quality": "数据不足，无法评估",
                "financial_analysis": {
                    "revenue_cagr": None,
                    "profit_margin": None,
                    "roe": None,
                    "debt_ratio": None
                },
                "risks": ["数据不足，无法分析风险"],
                "valuation": {
                    "current_pe": None,
                    "industry_average_pe": None,
                    "fair_value_range": "无法估算"
                },
                "investment_thesis": "数据不足，无法提供投资建议"
            }
    
    def _generate_company_profile(self, company_name: str, company_industry: str) -> str:
        """生成公司概况"""
        return f"{company_name}是一家专注于{company_industry}领域的企业，主要从事相关产品的研发、生产和销售业务。公司在行业内具有一定的市场地位和品牌影响力。"
    
    def _analyze_business_model(self, company_code: str, company_industry: str) -> str:
        """分析商业模式"""
        # 根据行业分析商业模式
        if company_industry == "科技":
            return "公司采用技术驱动型商业模式，通过持续研发创新保持产品竞争力，主要收入来源为产品销售和技术服务。公司注重知识产权保护，构建了较高的技术壁垒。"
        elif company_industry == "医疗":
            return "公司采用研发驱动型商业模式，通过持续的药物/医疗器械研发创造价值，收入主要来自产品销售和专利授权。公司拥有完整的研发、生产、销售体系。"
        elif company_industry == "消费":
            return "公司采用品牌驱动型商业模式，通过品牌建设和渠道拓展提升市场份额，收入主要来自产品销售。公司注重消费者体验和品牌价值提升。"
        elif company_industry == "金融":
            return "公司采用资本驱动型商业模式，通过提供金融服务和产品获取利差、手续费等收入。公司注重风险控制和客户资源积累。"
        else:
            return f"公司在{company_industry}行业采用综合型商业模式，结合产品销售和服务提供创造价值，主要收入来源为产品销售和相关服务。"
    
    def _analyze_products_services(self, company_code: str, company_industry: str) -> List[str]:
        """分析产品和服务"""
        # 根据行业分析产品和服务
        if company_industry == "科技":
            return ["硬件设备研发与销售", "软件系统开发与服务", "技术解决方案提供"]
        elif company_industry == "医疗":
            return ["药品研发与生产", "医疗器械销售", "医疗服务提供"]
        elif company_industry == "消费":
            return ["消费品研发与生产", "品牌运营与管理", "渠道建设与销售"]
        elif company_industry == "金融":
            return ["金融产品设计与销售", "资产管理服务", "风险管理咨询"]
        else:
            return [f"{company_industry}相关产品研发与销售", "行业解决方案提供", "售后服务与技术支持"]
    
    def _analyze_competitive_advantages(self, fundamentals: Dict[str, Any]) -> List[str]:
        """分析竞争优势"""
        advantages = []
        
        # 根据财务数据分析竞争优势
        if "profitability" in fundamentals:
            profitability = fundamentals["profitability"]
            
            if profitability.get("gross_margin", 0) > 0.3:
                advantages.append("较高毛利率，具有产品定价能力")
                
            if profitability.get("roe", 0) > 0.15:
                advantages.append("较高ROE，资本使用效率高")
                
            if profitability.get("net_margin", 0) > 0.15:
                advantages.append("较高净利率，成本控制能力强")
        
        if "growth" in fundamentals:
            growth = fundamentals["growth"]
            
            if growth.get("revenue_growth", 0) > 0.2:
                advantages.append("收入高速增长，市场拓展能力强")
                
            if growth.get("profit_growth", 0) > 0.2:
                advantages.append("利润高速增长，盈利能力持续提升")
        
        # 如果没有足够的优势，添加一些通用的
        if len(advantages) < 2:
            advantages.append("行业经验丰富，品牌认知度较高")
            advantages.append("研发投入持续，创新能力较强")
        
        return advantages[:3]  # 最多返回3个优势
    
    def _evaluate_management_quality(self, company_code: str, fundamentals: Dict[str, Any]) -> str:
        """评估管理层质量"""
        # 根据财务数据评估管理层质量
        management_score = 0
        
        if "profitability" in fundamentals:
            profitability = fundamentals["profitability"]
            
            if profitability.get("roe", 0) > 0.15:
                management_score += 1
                
            if profitability.get("roa", 0) > 0.08:
                management_score += 1
        
        if "growth" in fundamentals:
            growth = fundamentals["growth"]
            
            if growth.get("revenue_growth", 0) > 0.15:
                management_score += 1
                
            if growth.get("profit_growth", 0) > growth.get("revenue_growth", 0):
                management_score += 1
        
        if "solvency" in fundamentals:
            solvency = fundamentals["solvency"]
            
            if solvency.get("debt_to_equity", 0) < 0.5:
                management_score += 1
        
        # 根据得分评估管理层
        if management_score >= 4:
            return "管理层表现优秀，战略执行力强，财务管理稳健，公司治理结构完善。"
        elif management_score >= 2:
            return "管理层表现良好，经营策略合理，财务状况稳定，公司治理规范。"
        else:
            return "管理层表现一般，经营策略有待优化，财务管理需加强，公司治理有提升空间。"
    
    def _extract_financial_analysis(self, fundamentals: Dict[str, Any]) -> Dict[str, Optional[float]]:
        """提取财务分析数据"""
        # 使用显式的类型注解来避免类型错误
        financial_analysis: Dict[str, Optional[float]] = {
            "revenue_cagr": None,
            "profit_margin": None,
            "roe": None,
            "debt_ratio": None
        }
        
        # 从基本面数据中提取财务指标
        if "growth" in fundamentals:
            financial_analysis["revenue_cagr"] = fundamentals["growth"].get("revenue_growth")
        
        if "profitability" in fundamentals:
            financial_analysis["profit_margin"] = fundamentals["profitability"].get("net_margin")
            financial_analysis["roe"] = fundamentals["profitability"].get("roe")
        
        if "solvency" in fundamentals:
            financial_analysis["debt_ratio"] = fundamentals["solvency"].get("debt_to_equity")
        
        return financial_analysis
    
    def _analyze_risks(self, company_code: str, fundamentals: Dict[str, Any], technicals: Dict[str, Any]) -> List[str]:
        """分析风险因素"""
        risks = []
        
        # 分析财务风险
        if "solvency" in fundamentals:
            solvency = fundamentals["solvency"]
            
            if solvency.get("debt_to_equity", 0) > 1:
                risks.append("负债率较高，财务风险需关注")
                
            if solvency.get("current_ratio", 0) < 1:
                risks.append("流动比率偏低，短期偿债压力大")
        
        # 分析经营风险
        if "profitability" in fundamentals:
            profitability = fundamentals["profitability"]
            
            if profitability.get("gross_margin", 0) < 0.2:
                risks.append("毛利率较低，抗风险能力弱")
        
        # 分析技术面风险
        if "trend_analysis" in technicals:
            trend = technicals["trend_analysis"]
            
            if trend.get("overall_trend") == "强势下跌":
                risks.append("股价处于下跌趋势，市场情绪悲观")
                
            if trend.get("overbought", False):
                risks.append("技术指标显示超买，短期回调风险高")
        
        # 如果没有足够的风险，添加一些通用的
        if len(risks) < 2:
            risks.append("行业竞争加剧，市场份额面临挑战")
            risks.append("宏观经济波动可能影响业绩表现")
            risks.append("政策法规变化可能带来合规成本增加")
        
        return risks[:3]  # 最多返回3个风险
    
    def _extract_valuation_data(self, valuation: Dict[str, Any], company_industry: str) -> Dict[str, Any]:
        """提取估值数据"""
        valuation_data = {
            "current_pe": valuation.get("pe_ttm"),
            "industry_average_pe": None,
            "fair_value_range": "无法估算"
        }
        
        # 设置行业平均PE
        if company_industry == "科技":
            valuation_data["industry_average_pe"] = 35.0
        elif company_industry == "医疗":
            valuation_data["industry_average_pe"] = 40.0
        elif company_industry == "消费":
            valuation_data["industry_average_pe"] = 30.0
        elif company_industry == "金融":
            valuation_data["industry_average_pe"] = 10.0
        else:
            valuation_data["industry_average_pe"] = 20.0
        
        # 计算公允价值区间
        if valuation.get("fair_value") and valuation.get("pe_ttm"):
            fair_value = valuation["fair_value"]
            current_price = fair_value / (valuation["pe_ttm"] / valuation_data["industry_average_pe"])
            lower_bound = round(current_price * 0.9, 2)
            upper_bound = round(current_price * 1.1, 2)
            valuation_data["fair_value_range"] = f"{lower_bound}-{upper_bound}元"
        
        return valuation_data
    
    def _generate_investment_thesis(self, company_name: str, fundamentals: Dict[str, Any],
                                   technicals: Dict[str, Any], valuation: Dict[str, Any]) -> str:
        """生成投资论点"""
        # 评估基本面
        fundamental_strength = "强"
        if "profitability" in fundamentals:
            roe = fundamentals["profitability"].get("roe", 0)
            if roe < 0.1:
                fundamental_strength = "弱"
            elif roe < 0.15:
                fundamental_strength = "中"
        
        # 评估技术面
        technical_strength = "中性"
        if "trend_analysis" in technicals:
            trend = technicals["trend_analysis"].get("overall_trend", "")
            if "上涨" in trend:
                technical_strength = "看涨"
            elif "下跌" in trend:
                technical_strength = "看跌"
        
        # 评估估值
        valuation_assessment = "合理"
        pe_ttm = valuation.get("pe_ttm", 0)
        if pe_ttm:
            if pe_ttm > 40:
                valuation_assessment = "偏高"
            elif pe_ttm < 15:
                valuation_assessment = "偏低"
        
        # 生成投资建议
        if fundamental_strength == "强" and (technical_strength == "看涨" or valuation_assessment == "偏低"):
            recommendation = "买入"
            thesis = f"{company_name}基本面{fundamental_strength}劲，技术面{technical_strength}，估值{valuation_assessment}，具有较好的投资价值。公司在行业内竞争优势明显，盈利能力强，成长性好，建议投资者积极关注。"
        elif fundamental_strength == "中" and technical_strength != "看跌" and valuation_assessment != "偏高":
            recommendation = "增持"
            thesis = f"{company_name}基本面{fundamental_strength}等，技术面{technical_strength}，估值{valuation_assessment}，具有一定投资价值。公司经营稳健，但成长性一般，建议投资者适度配置。"
        elif fundamental_strength == "弱" or (technical_strength == "看跌" and valuation_assessment == "偏高"):
            recommendation = "观望"
            thesis = f"{company_name}基本面{fundamental_strength}，技术面{technical_strength}，估值{valuation_assessment}，投资价值有限。建议投资者保持观望，等待更好的买入时机。"
        else:
            recommendation = "持有"
            thesis = f"{company_name}基本面{fundamental_strength}，技术面{technical_strength}，估值{valuation_assessment}。公司经营状况稳定，建议投资者持有观望，关注公司后续发展动态。"
        
        return thesis
    
    def _research_theme(self, theme: str) -> Dict[str, Any]:
        """
        主题研究
        
        参数:
            theme: 研究主题
            
        返回:
            主题研究报告
        """
        logger.info(f"研究主题: {theme}")
        
        try:
            # 获取数据收集器
            data_collector = DataCollector()
            
            # 根据主题关键词筛选相关公司
            related_companies = self._find_related_companies(theme)
            
            # 生成主题概述
            theme_overview = self._generate_theme_overview(theme)
            
            # 估计市场规模
            market_size = self._estimate_market_size(theme)
            
            # 分析产业链
            value_chain = self._analyze_value_chain(theme)
            
            # 技术评估
            technology_assessment = self._assess_technology(theme)
            
            # 采用时间线
            adoption_timeline = self._generate_adoption_timeline(theme)
            
            # 寻找投资机会
            investment_opportunities = self._find_investment_opportunities(theme, related_companies)
            
            # 生成总体建议
            recommendation = self._generate_recommendation(theme, investment_opportunities)
            
            return {
                "theme_overview": theme_overview,
                "market_size": market_size,
                "key_players": [company["name"] for company in related_companies[:3]],
                "value_chain": value_chain,
                "technology_assessment": technology_assessment,
                "adoption_timeline": adoption_timeline,
                "investment_opportunities": investment_opportunities,
                "recommendation": recommendation
            }
            
        except Exception as e:
            logger.error(f"主题研究失败: {e}")
            # 返回基本信息
            return {
                "theme_overview": f"{theme}主题概述 (数据获取失败)",
                "market_size": "数据不足，无法估计市场规模",
                "key_players": ["数据不足"],
                "value_chain": "数据不足，无法分析产业链",
                "technology_assessment": "数据不足，无法评估技术",
                "adoption_timeline": "数据不足，无法生成采用时间线",
                "investment_opportunities": [],
                "recommendation": "数据不足，无法提供投资建议"
            }
    
    def _find_related_companies(self, theme: str) -> List[Dict[str, str]]:
        """查找与主题相关的公司"""
        try:
            # 获取股票列表
            data_collector = DataCollector()
            stock_list = data_collector.get_stock_list()
            
            # 主题关键词映射
            theme_keywords = {
                "人工智能": ["AI", "人工智能", "机器学习", "深度学习", "算法", "智能"],
                "新能源": ["新能源", "光伏", "风电", "储能", "氢能", "电动"],
                "半导体": ["芯片", "半导体", "集成电路", "晶圆", "封装"],
                "消费升级": ["消费", "品牌", "零售", "电商", "奢侈品"],
                "医疗创新": ["医疗", "生物", "药物", "疫苗", "诊断", "器械"],
                "数字经济": ["数字", "互联网", "云计算", "大数据", "平台"],
                "智能制造": ["智能制造", "工业互联网", "自动化", "机器人"],
                "元宇宙": ["元宇宙", "虚拟现实", "VR", "AR", "游戏"],
                "金融科技": ["金融科技", "支付", "区块链", "保险科技"]
            }
            
            # 获取主题关键词
            keywords = []
            for key, values in theme_keywords.items():
                if theme in values or key == theme:
                    keywords.extend(values)
            
            # 如果没有找到匹配的关键词，使用主题本身作为关键词
            if not keywords:
                keywords = [theme]
            
            # 筛选相关公司
            related_companies = []
            
            if not stock_list.empty:
                for _, row in stock_list.iterrows():
                    company_name = row.get('name', '')
                    company_desc = row.get('description', '')
                    company_industry = row.get('industry', '')
                    
                    # 检查公司名称、描述和行业是否包含关键词
                    for keyword in keywords:
                        if (keyword in company_name or
                            (isinstance(company_desc, str) and keyword in company_desc) or
                            (isinstance(company_industry, str) and keyword in company_industry)):
                            related_companies.append({
                                "code": row.get('code', ''),
                                "name": company_name,
                                "industry": company_industry
                            })
                            break
            
            # 如果没有找到相关公司，返回行业内的代表性公司
            if not related_companies:
                if "人工智能" in theme or "AI" in theme:
                    return [
                        {"code": "000063", "name": "中兴通讯", "industry": "科技"},
                        {"code": "002415", "name": "海康威视", "industry": "科技"},
                        {"code": "600100", "name": "同方股份", "industry": "科技"}
                    ]
                elif "新能源" in theme:
                    return [
                        {"code": "300750", "name": "宁德时代", "industry": "新能源"},
                        {"code": "601012", "name": "隆基绿能", "industry": "新能源"},
                        {"code": "002594", "name": "比亚迪", "industry": "新能源"}
                    ]
                elif "医疗" in theme or "生物" in theme:
                    return [
                        {"code": "600276", "name": "恒瑞医药", "industry": "医疗"},
                        {"code": "300015", "name": "爱尔眼科", "industry": "医疗"},
                        {"code": "688180", "name": "君实生物", "industry": "医疗"}
                    ]
                else:
                    return [
                        {"code": "600519", "name": "贵州茅台", "industry": "消费"},
                        {"code": "601318", "name": "中国平安", "industry": "金融"},
                        {"code": "600036", "name": "招商银行", "industry": "金融"}
                    ]
            
            return related_companies
            
        except Exception as e:
            logger.error(f"查找相关公司失败: {e}")
            return [
                {"code": "000001", "name": "示例公司1", "industry": "相关行业"},
                {"code": "000002", "name": "示例公司2", "industry": "相关行业"},
                {"code": "000003", "name": "示例公司3", "industry": "相关行业"}
            ]
    
    def _generate_theme_overview(self, theme: str) -> str:
        """生成主题概述"""
        # 根据主题生成概述
        if "人工智能" in theme or "AI" in theme:
            return "人工智能是当前科技发展的重要方向，涵盖机器学习、深度学习、自然语言处理等多个领域。随着算力提升和算法突破，AI技术正加速渗透到各行各业，推动产业智能化升级。中国在AI领域的投入和应用不断加强，相关政策支持力度大，市场前景广阔。"
        elif "新能源" in theme:
            return "新能源产业是全球能源转型的核心，包括光伏、风电、储能、氢能等多个细分领域。在碳中和目标驱动下，新能源产业迎来快速发展期。中国在光伏、风电等领域已具备全球竞争力，产业链日趋完善，技术创新不断突破，市场规模持续扩大。"
        elif "半导体" in theme or "芯片" in theme:
            return "半导体产业是现代信息社会的基础，涵盖设计、制造、封装测试等多个环节。在国产化替代和数字经济发展的双重驱动下，中国半导体产业迎来发展机遇。虽然在先进制程领域仍有差距，但在成熟工艺和特色工艺领域已取得显著进展，产业生态逐步完善。"
        elif "消费升级" in theme:
            return "消费升级是中国经济转型的重要方向，体现在消费者对品质、体验、个性化需求的提升。国内品牌崛起、新零售模式创新、线上线下融合等趋势明显。随着中产阶级扩大和消费观念变化，高品质、差异化、智能化的产品和服务将获得更大市场空间。"
        elif "医疗" in theme or "生物" in theme:
            return "医疗创新是提升国民健康水平的关键，涵盖创新药、高端医疗器械、生物技术等多个领域。在政策支持和市场需求的双重驱动下，中国医疗创新步伐加快。创新药研发取得突破，医疗器械国产化加速，互联网医疗等新模式快速发展，行业整体呈现高质量发展态势。"
        else:
            return f"{theme}是当前市场关注的重要投资主题，涉及多个行业和领域。在政策支持和市场需求的推动下，相关产业正经历快速发展和转型升级。随着技术创新和商业模式演进，该主题下的企业面临广阔的发展空间和投资机会。"
    
    def _estimate_market_size(self, theme: str) -> str:
        """估计市场规模"""
        # 根据主题估计市场规模
        if "人工智能" in theme or "AI" in theme:
            return "根据权威机构预测，全球人工智能市场规模预计从2023年的1500亿美元增长到2030年的超过1.8万亿美元，年均复合增长率约42%。中国AI市场规模预计2025年将超过4000亿元，在计算机视觉、语音识别等领域已形成完整产业链。"
        elif "新能源" in theme:
            return "全球新能源市场规模预计从2023年的1.2万亿美元增长到2030年的3.5万亿美元，年均复合增长率约16.5%。中国作为全球最大的新能源市场，光伏装机容量连续多年全球第一，新能源汽车产销量全球领先，储能市场增速超过200%。"
        elif "半导体" in theme or "芯片" in theme:
            return "全球半导体市场规模预计从2023年的5500亿美元增长到2030年的1万亿美元，年均复合增长率约8.5%。中国是全球最大的半导体消费市场，国内半导体产业规模预计2025年将超过1.3万亿元，自给率有望从目前的20%提升到35%左右。"
        elif "消费升级" in theme:
            return "中国消费升级市场规模巨大，高端消费品市场预计2025年将达到1.2万亿元，年均复合增长率约12%。新兴消费领域如智能家居、健康管理、体验式消费等增长迅速，国货品牌崛起趋势明显，消费结构持续优化。"
        elif "医疗" in theme or "生物" in theme:
            return "全球医疗创新市场规模预计从2023年的1.8万亿美元增长到2030年的3.2万亿美元，年均复合增长率约8.5%。中国医疗健康产业规模预计2025年将超过12万亿元，创新药、高端医疗器械、基因技术等细分领域增速显著，医疗服务模式创新加速。"
        else:
            return f"{theme}相关市场规模可观，预计未来5年将保持15-20%的年均复合增长率。随着技术进步、政策支持和市场需求增长，该领域的投资价值将持续提升。产业链上下游协同发展，龙头企业市场份额有望进一步提高。"
    
    def _analyze_value_chain(self, theme: str) -> str:
        """分析产业链"""
        # 根据主题分析产业链
        if "人工智能" in theme or "AI" in theme:
            return "AI产业链包括基础层(算力、算法、数据)、技术层(计算机视觉、语音识别、自然语言处理等)和应用层(智能制造、智慧医疗、智能金融等)。上游算力环节竞争格局相对集中，中游算法平台呈现寡头竞争，下游应用场景丰富多元，各细分领域正涌现一批创新企业。"
        elif "新能源" in theme:
            return "新能源产业链包括上游原材料(多晶硅、锂矿等)、中游制造(电池、组件、逆变器等)和下游应用(电站运营、系统集成等)。光伏领域中国企业已实现全产业链布局，风电领域整机制造和零部件国产化率高，储能领域电池技术领先但系统集成有待提升。"
        elif "半导体" in theme or "芯片" in theme:
            return "半导体产业链包括上游设计(IP核、EDA工具)、中游制造(晶圆制造、材料)和下游封装测试。中国在设计环节已有一批领先企业，制造环节在成熟工艺领域取得突破，封装测试环节具备全球竞争力。产业链协同度不断提升，但核心环节对外依存度仍较高。"
        elif "消费升级" in theme:
            return "消费升级产业链包括上游品牌商、中游渠道商和下游消费者。品牌商负责产品研发和品牌建设，渠道商包括线上平台和线下零售，消费者决策受社交媒体和KOL影响显著。新消费品牌崛起路径多元化，数字化营销和精准获客成为关键能力。"
        elif "医疗" in theme or "生物" in theme:
            return "医疗创新产业链包括上游研发(药物发现、临床试验)、中游生产(药品/器械制造)和下游销售(医院、药店、电商)。创新药领域研发投入持续增加，CRO/CDMO服务蓬勃发展；医疗器械国产替代加速；医疗服务模式创新丰富，互联网医疗打破传统就医流程。"
        else:
            return f"{theme}产业链包括上游原材料/技术供应商、中游产品/服务提供商和下游应用/消费场景。产业链各环节协同发展，技术创新和商业模式创新并重。龙头企业通过垂直整合或专业化经营构建竞争优势，产业集中度有望进一步提升。"
    
    def _assess_technology(self, theme: str) -> str:
        """技术评估"""
        # 根据主题评估技术
        if "人工智能" in theme or "AI" in theme:
            return "AI技术正处于快速发展期，大模型、多模态融合、联邦学习等前沿技术不断突破。算力提升和数据积累推动模型规模指数级增长，通用AI与专用AI协同发展。中国在计算机视觉、语音识别等领域已达国际先进水平，但在基础理论和原创算法方面仍有差距。"
        elif "新能源" in theme:
            return "新能源技术创新活跃，光伏领域N型电池、异质结等高效电池技术加速商业化；风电领域大型化、智能化趋势明显；储能领域钠离子电池、固态电池等新技术取得突破。中国在光伏制造技术领先全球，风电整机技术接近国际先进水平，储能技术创新加速。"
        elif "半导体" in theme or "芯片" in theme:
            return "半导体技术迭代加速，先进制程向3nm以下推进，摩尔定律延续；先进封装、第三代半导体等特色工艺蓬勃发展。中国在成熟制程和特色工艺领域取得突破，28nm及以上工艺实现量产，但在EUV光刻、高端设备等领域仍存在技术瓶颈。"
        elif "消费升级" in theme:
            return "消费技术创新主要体现在产品智能化、个性化和体验升级。智能家居、可穿戴设备等新品类快速发展；数字化、社交化营销技术提升获客效率；供应链柔性化技术支持小批量、多品类生产。中国品牌在产品创新和营销创新方面已具备全球竞争力。"
        elif "医疗" in theme or "生物" in theme:
            return "医疗技术创新加速，基因编辑、细胞治疗、AI辅助诊断等前沿技术取得突破。创新药研发效率提升，靶向药物、免疫治疗等领域进展显著；高端医疗器械国产化加速；数字医疗技术打破传统诊疗模式。中国在部分领域已接近国际先进水平，但原创性突破仍需加强。"
        else:
            return f"{theme}相关技术正处于快速发展期，创新成果不断涌现。技术迭代周期缩短，跨领域融合趋势明显，产学研协同创新生态逐步完善。中国企业在技术研发投入和专利申请方面表现活跃，部分细分领域已具备全球竞争力。"
    
    def _generate_adoption_timeline(self, theme: str) -> str:
        """生成采用时间线"""
        # 根据主题生成采用时间线
        if "人工智能" in theme or "AI" in theme:
            return "AI技术采用将分阶段推进：2023-2025年是大模型应用爆发期，AIGC、智能客服等场景率先落地；2026-2028年是产业智能化深化期，制造、医疗、金融等垂直领域应用成熟；2029年后将进入普惠AI时代，AI技术将无处不在，与传统产业深度融合。"
        elif "新能源" in theme:
            return "新能源采用将持续加速：2023-2025年是规模化发展期，光伏、风电装机量快速增长，新能源汽车渗透率提升；2026-2028年是系统化整合期，多能互补、源网荷储协同发展；2029年后将进入高比例新能源时代，化石能源占比显著下降。"
        elif "半导体" in theme or "芯片" in theme:
            return "半导体国产化将稳步推进：2023-2025年是成熟工艺突破期，28nm及以上工艺实现规模量产；2026-2028年是先进工艺追赶期，14nm工艺产能提升，7nm工艺取得突破；2029年后有望在部分领域实现技术引领，特色工艺和第三代半导体领域形成优势。"
        elif "消费升级" in theme:
            return "消费升级将持续演进：2023-2025年是品质消费普及期，国货品牌崛起，高端化趋势明显；2026-2028年是体验消费深化期，沉浸式、社交化消费模式创新；2029年后将进入个性化定制时代，消费者参与产品设计和生产过程，C2M模式成熟。"
        elif "医疗" in theme or "生物" in theme:
            return "医疗创新将加速落地：2023-2025年是创新药放量期，PD-1等重磅药物国产化；2026-2028年是精准医疗普及期，基因检测和个性化治疗方案推广；2029年后将进入智慧医疗时代，AI辅助诊疗成为标准，远程医疗和家庭医疗设备普及。"
        else:
            return f"{theme}相关技术和产品采用将经历三个阶段：近期(1-2年)是市场教育和早期应用阶段，创新产品开始商业化；中期(3-5年)是规模化发展阶段，商业模式成熟，市场渗透率提升；远期(5年以上)是普及和融合阶段，技术和应用全面成熟，形成新的产业生态。"
    
    def _find_investment_opportunities(self, theme: str, related_companies: List[Dict[str, str]]) -> List[Dict[str, str]]:
        """寻找投资机会"""
        investment_opportunities = []
        
        # 根据主题和相关公司寻找投资机会
        for i, company in enumerate(related_companies[:3]):  # 最多取前3家公司
            company_code = company.get("code", "")
            company_name = company.get("name", "")
            company_industry = company.get("industry", "")
            
            # 生成投资理由
            if "人工智能" in theme or "AI" in theme:
                thesis = f"{company_name}在AI领域具有核心技术优势，产品市场认可度高，有望受益于AI应用爆发。"
            elif "新能源" in theme:
                thesis = f"{company_name}在新能源产业链中占据关键位置，技术领先，成本控制能力强，增长确定性高。"
            elif "半导体" in theme or "芯片" in theme:
                thesis = f"{company_name}在半导体领域具有自主创新能力，国产替代空间大，政策支持力度强，成长潜力显著。"
            elif "消费升级" in theme:
                thesis = f"{company_name}把握消费升级趋势，品牌力强，产品创新能力突出，渠道布局完善，市场份额有望提升。"
            elif "医疗" in theme or "生物" in theme:
                thesis = f"{company_name}在医疗创新领域研发管线丰富，商业化能力强，产品差异化优势明显，成长空间广阔。"
            else:
                thesis = f"{company_name}在{theme}领域具有先发优势，核心竞争力突出，行业地位稳固，有望充分受益于行业发展。"
            
            investment_opportunities.append({
                "company": company_name,
                "code": company_code,
                "industry": company_industry,
                "thesis": thesis
            })
        
        return investment_opportunities
    
    def _generate_recommendation(self, theme: str, investment_opportunities: List[Dict[str, str]]) -> str:
        """生成总体建议"""
        # 根据主题和投资机会生成总体建议
        if not investment_opportunities:
            return f"建议投资者关注{theme}主题的龙头企业，把握行业成长机遇。"
        
        company_names = [opp["company"] for opp in investment_opportunities[:2]]
        company_str = "、".join(company_names)
        
        if "人工智能" in theme or "AI" in theme:
            return f"AI主题投资建议关注三条主线：算力基础设施、模型开发平台和垂直应用场景。建议重点配置{company_str}等具备核心技术和应用落地能力的企业，把握AI大模型商业化浪潮。"
        elif "新能源" in theme:
            return f"新能源主题投资建议关注高景气度细分领域和具备技术壁垒的环节。建议重点配置{company_str}等产业链地位稳固、成本控制能力强的龙头企业，把握能源转型长期机遇。"
        elif "半导体" in theme or "芯片" in theme:
            return f"半导体主题投资建议关注国产替代空间大、技术突破明显的细分领域。建议重点配置{company_str}等研发投入持续、客户认证进展顺利的企业，把握产业升级和自主可控趋势。"
        elif "消费升级" in theme:
            return f"消费升级主题投资建议关注品牌力强、产品创新能力突出的企业。建议重点配置{company_str}等把握消费者需求变化、渠道布局完善的公司，分享消费结构优化红利。"
        elif "医疗" in theme or "生物" in theme:
            return f"医疗创新主题投资建议关注研发管线丰富、商业化能力强的企业。建议重点配置{company_str}等在细分领域具备差异化优势的公司，把握医疗健康产业升级机遇。"
        else:
            return f"{theme}主题投资建议关注行业领先企业和创新型公司。建议重点配置{company_str}等在细分领域具备核心竞争力的企业，把握产业发展和技术创新带来的投资机会。"